﻿using System;
using System.Collections.Generic;
using System.Data.OracleClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Resource;
using System.Data;
using System.Configuration;
using Logger;
using Models;
using Utility;
using Service.Interface;

namespace Service.Impl
{
    public class OaServices : IOaServices
    {
        private static readonly string useremailinfo = ConfigurationManager.AppSettings["OA_UserEmailInfo"];
        private static readonly string sender = ConfigurationManager.AppSettings["OaDocumentDAO_Email"];
        
        public Result Mergeinto(OaDocument document)
        {
            //版本维护
            List<OracleParameter> parms = new List<OracleParameter>()
            {
                new OracleParameter(":ID",OracleType.VarChar){ Value=document.Id},
                new OracleParameter(":VERSION",OracleType.VarChar){ Value=document.Version},
                new OracleParameter(":NAME",OracleType.VarChar){ Value=document.Name},
                new OracleParameter(":CREATE_DATE",OracleType.DateTime){ Value=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},
                new OracleParameter(":MODIFY_DATE",OracleType.DateTime){ Value=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}
            };
            string str = $@"
			MERGE INTO OA_DOCUMENT T 
			USING DUAL ON (T.ID = :ID)
			WHEN MATCHED THEN
			UPDATE 
				SET T.VERSION = :VERSION,
					T.NAME = :NAME,
					T.MODIFY_DATE = :MODIFY_DATE 
			WHERE T.VERSION <> :VERSION
			WHEN NOT MATCHED THEN
				INSERT ( ID, VERSION, NAME, CREATE_DATE,MODIFY_DATE )
				VALUES (:ID,:VERSION,:NAME,:CREATE_DATE,:MODIFY_DATE )";
            var status = FOracleHelper.ExecuteNonQuery(str.Replace(@"[\r\n]", ""), parms.ToArray()) > 0;
            
            //通知人员
            List<OracleParameter> parmt = new List<OracleParameter>()
            {
                new OracleParameter(":TRAINNING_FILE",OracleType.VarChar){ Value=document.Id}
            };
            string tra = $@"
            SELECT
                RANK() OVER(ORDER BY OPERATOR) AS INDES,
	            DEPT,
	            OPERATOR,
	            OPERATOR_NAME,
	            OPERATOR_LEADER,
	            PRODUCT,
	            PROCESS_NAME,
	            PROJ_CODE,
	            TRAINNING_FILE,
	            TRAINNING_FILE_VERSION,
                '{document.Version}' AS NEW_VERSION,
	            TRAINNING_TEACHER 
            FROM
	            PROCESS_ITEM_LIST_OPERATOR 
            WHERE
	            STATUS = 1 --生效
	            AND TRAINNING_FILE = :TRAINNING_FILE 
            ORDER BY OPERATOR,
	            PRODUCT,
	            PROCESS_NAME ";
            var dt = FOracleHelper.ExecuteDt(tra.Replace(@"[\r\n]", ""), parmt.ToArray());
            if (dt.Rows.Count > 0)
            {
                //// 1、接口过滤离职人员
                //var employelist = (from d in dt.AsEnumerable() select new { EmployeNum = d.Field<string>("OPERATOR") }).Distinct().ToArray();
                //Dictionary<object, object> dic = new Dictionary<object, object>();
                //dic.Add("Branch", 27);
                //dic.Add("EmployeList", employelist);
                //var rturndata = HttpHelper.HttpPost(useremailinfo, "POST", "application/json", GeneralMethod.ToJson(dic));
                ////获取有效的数据
                //var rtndic = GeneralMethod.JsonReverse<Dictionary<object, object>>(rturndata);
                List<string> branchemailaddress = new List<string>();
                //List<string> employenum = new List<string>();
                //foreach (var item in rtndic)
                //{
                //    var value = GeneralMethod.JsonReverse<List<object>>(item.Value.ToString());
                //    for (int i = 0; i < value.Count; i++)
                //    {
                //        var pam = GeneralMethod.JsonJObject(value[i].ToString());
                //        if (item.Key.Equals("EmailBranch"))
                //        {
                //            branchemailaddress.Add(pam["EmailAddress"].ToString());
                //        }
                //        if (item.Key.Equals("EmployeList"))
                //        {
                //            if (Convert.ToBoolean(pam["Status"]))
                //            {
                //                employenum.Add(pam["EmployeNum"].ToString());
                //            }
                //        }
                //    }
                //}

                var creldata = (from d in dt.AsEnumerable() /*where employenum.Contains(d.Field<string>("OPERATOR"))*/ select d);
                //复制dt结构
                var clonedt = dt.Clone();
                foreach (var item in creldata)
                {
                    clonedt.Rows.Add(item.ItemArray);
                }
                if (clonedt.Rows.Count > 0)
                {
                    StringBuilder tabletr = new StringBuilder();
                    for (int r = 0; r < clonedt.Rows.Count; r++)
                    {
                        StringBuilder tabletd = new StringBuilder();
                        for (int c = 0; c < clonedt.Columns.Count; c++)
                        {
                            if (clonedt.Columns[c].ToString().Equals("INDES"))
                            {
                                tabletd.Append(string.Format(Msg.EmailTableTd, r));
                            }
                            else
                            {
                                tabletd.Append(string.Format(Msg.EmailTableTd, clonedt.Rows[r][clonedt.Columns[c]]));
                            }
                        }
                        tabletr.Append(string.Format(Msg.EmailTableTr, tabletd));
                    }
                    // 2、接口获取邮件发送人 系统邮件通知： MFG主管和经理、HR 李思民和经理、QA 主管和经理 + 苏平平
                    var senderlist =  sender.TrimEnd(';').Split(';').ToList();
                    var emailsenderlist = branchemailaddress.Union(senderlist).ToList<string>();
                    StringBuilder body = new StringBuilder();
                    body.Append(Msg.EmailStyle);
                    body.Append(string.Format(Msg.EmailTitle, Msg.TrainingEmailContent));
                    body.Append(string.Format(Msg.EmailTable, Msg.TrainingEmailTableTh, tabletr));
                    EmailHelper.SendToEmail(emailsenderlist, Msg.TrainingNotice, body.ToString());
                    //LogHelper.Log(LogTarget.FisWebApi, "OaDocumentDAO邮件通知：" + rturndata);
                }
            }
            Result result = new Result(status);
            if (!status)
            {
                result.ReturnMessage = string.Format(Msg.ThisExist, document.Version);
            }
            return result;
        }
    }
}
